package com.gnerv.tools.entity.extend.utils.mapper;

import com.gnerv.tools.entity.extend.annotation.EntityExtend;
import com.gnerv.tools.extity.extend.autoconfigure.ExtendConfigProperties;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class ResultMappingUtils {

    private static String EXTEND = "extend";

    private ResultMappingUtils() {
    }

    public static List<ResultMapping> buildResultMapping(MappedStatement ms, Set<EntityExtend> entityExtends) {
        List<ResultMapping> lists = buildResultMapping(ms, Object.class, entityExtends);
        return lists;
    }

    public static List<ResultMapping> buildResultMapping(MappedStatement ms, Class<?> javaType, Set<EntityExtend> entityExtends) {
        List<ResultMapping> resultMappings = ms.getResultMaps().get(0).getResultMappings();
        List lists = new ArrayList(resultMappings);
        for (EntityExtend entityExtend : entityExtends) {
            ResultMapping resultMapping =
                    new ResultMapping.Builder(ms.getConfiguration(), EXTEND, entityExtend.column(), entityExtend.resultType())
                            .nestedResultMapId(null)
                            .nestedQueryId(entityExtend.selectMethod())
                            .composites(CompositesUtils.buildExtendComposites(ms, entityExtend))
                            .build();
            lists.add(resultMapping);
        }
        return lists;
    }


    public static List<ResultMapping> buildMapResultMapping(MappedStatement ms, Class<?> javaType) {
        List<ResultMapping> resultMappings = ms.getResultMaps().get(0).getResultMappings();
        List lists = new ArrayList(resultMappings);
        ResultMapping resultMapping =
                new ResultMapping.Builder(ms.getConfiguration(), EXTEND).javaType(javaType)
                        .nestedResultMapId(ResultMapUtils.buildExtendResultMapId(ms))
                        .notNullColumns(new HashSet())
                        .build();
        lists.add(resultMapping);
        return lists;
    }


}
